from flask import render_template, jsonify
import random
import hashlib
from app.config import website_config

''' 自定义模板过滤器 '''
def my_template_filter(app):

    def my_repeat(length):
        return '|--' + (length * '----')

    def get_option(name, default=None):
        return website_config.get(name) or default
    
    app.add_template_filter(my_repeat, "my_repeat")
    app.add_template_global(get_option, "get_option")

'''初始化全局错误'''
def init_error_handle(app, db):
    # 全局404跳转
    @app.errorhandler(404)
    def page_not_found(e):
        return render_template("errors/404.html")

    # 表单令牌错误
    @app.errorhandler(400)
    def page_400(e):
        return jsonify({"code": 400, "msg": "The CSRF token is missing."})
    
    # 关闭数据库
    @app.teardown_appcontext
    def shutdown_session(exception=None):
        db.session.remove()
        

''' 随机生成指定长度字符串 '''
def create_nonce_str(length = 6):
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return "".join(random.sample(chars, length))

''' md5加密 '''
def md5(str):
    md5 = hashlib.md5()
    md5.update(str.encode('utf-8'))
    return md5.hexdigest()

''' 创建用户密码 '''
def create_password(password, salt):
    return md5(md5(password) + salt)

''' 生成树 '''
def generate_tree(data, parent_id = 0, is_dict = False):
    tree = []
    if is_dict == True:
        for item in data:
            if item['parent_id'] == parent_id:
                item['children'] = generate_tree(data, item['id'], is_dict)
                tree.append(item)
    else:
        for item in data:
            if item.parent_id == parent_id:
                item.children = generate_tree(data, item.id, is_dict)
                tree.append(item)
    return tree

''' 无限分类 '''
def generate_tree2(return_data, data, parent_id = 0, level = 0):
    for item in data:
        if item.parent_id == parent_id:
            item.level = level
            return_data.append(item)
            generate_tree2(return_data, data, item.id, level + 1)
    
    return return_data

''' 获取表单数组值 '''
def get_form_input_array(request, name):
    data = []
    for input_name in request.form:
        if str(input_name).startswith(name):
            input_value = request.form.get(input_name)
            data.append(input_value)
    return data